﻿using PLCSharp.CoreModel.Common;
using PLCSharp.CoreModel.Prism;
using PLCSharp.CoreModel.UserControls;
using PLCSharp.Models;
using PLCSharp.Views.Workflows.Script;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Windows.Media;
using System.Windows.Shapes;

namespace PLCSharp.Views.Workflows
{
    public class WorkflowConfigViewModel : DialogAwareBase
    {
        public WorkflowConfigViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)

        {
            GlobalModel = container.Resolve<GlobalModel>();
        }

        private AsyncDelegateCommand _Save;
        public AsyncDelegateCommand Save =>
            _Save ??= new AsyncDelegateCommand(ExecuteSaveAsync);

        private async Task ExecuteSaveAsync()
        {
            await CustomTextEditor.FormatCodeAsync();
            GlobalModel.WorkflowsModel.Manage.Execute("Save");

        }

        private AsyncDelegateCommand _Compile;
        public AsyncDelegateCommand Compile =>
            _Compile ??= new AsyncDelegateCommand(ExecuteCompileAsync);

        private async Task ExecuteCompileAsync()
        {

            await CustomTextEditor.FormatCodeAsync();
            GlobalModel.WorkflowsModel.Manage.Execute("Save");
            SelectedFlowTask.Compile.Execute();
        }

        private Workflow _SelectedFlowTask;
        /// <summary>
        /// 
        /// </summary>
        public Workflow SelectedFlowTask
        {
            get { return _SelectedFlowTask; }
            set { SetProperty(ref _SelectedFlowTask, value); }
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            SelectedFlowTask = parameters.GetValue<Workflow>("SelectedTask");
        }

        private DelegateCommand _Run;
        public DelegateCommand Run =>
            _Run ??= new DelegateCommand(ExecuteRun);

        void ExecuteRun()
        {
            if (SelectedFlowTask.AutomaticExecution == false)
            {
                SelectedFlowTask.Run(GlobalModel);
            }
            else
            {
                System.Windows.MessageBox.Show("自动运行中，不能手动运行!"); ;
            }
        }
        readonly GlobalModel GlobalModel;


        private DelegateCommand<string> _FastEntry;
        public DelegateCommand<string> FastEntry =>
            _FastEntry ??= new DelegateCommand<string>(ExecuteFastEntry);

        void ExecuteFastEntry(string cmd)
        {
            switch (cmd)
            {
                case "网络收发":
                    CustomTextEditor.Insert(@"
                        case 0:
                            {
                                var connect = globalModel.GetConnect(""网络连接名"");
                                _ = connect.SendAsync(""要发送的消息""); 
                                flow.Step++;
                            }
                        break;
                        case 1:
                            {
                                var connect = globalModel.GetConnect(""网络连接名"");
                                if (string.IsNullOrEmpty(connect.ReceiveInfo))
                                    {
                                        var receiveInfo = globalModel.GetVariable(""全局变量名"");
                                        receiveInfo.Value = connect.ReceiveInfo;
                                        connect.ReceiveInfo = """";
                                        flow.Step++;
                                    }
                            }
                        break;
                    ");
                    break;

                case "视觉功能":
                    CustomTextEditor.Insert(@"
                        case 0:
                            {
                                var vf = globalModel.GetVisionFunction(""视觉功能名"");
                                vf.Flow.Reset();
                                flow.Step++;
                            }
                           break;
                        case 1:
                            {
                                var vf = globalModel.GetVisionFunction(""视觉功能名""); if( vf.RunAll(vf.Flow))
                                {
                                    flow.Step++;

                                }else if (flow.CheckStepTime(3))
                                     throw new Exception(""视觉功能超时!"");
                                }     
                            }                       

                            break;
                    ");
                    break;
                case "显示状态":
                    CustomTextEditor.Insert(@"
                        case 0:
                            {
                                var stateControl = globalModel.GetCustomControl(""控件名称"");
                                stateControl.Params.CellInfos[0].State = CellState.OK;
                                flow.Step++;
                            }
                        break;
                    ");
                    break;
                case "显示图片":
                    CustomTextEditor.Insert(@"
                    case 0:
                    {
                        var imageControl = globalModel.GetCustomControl(""控件名称"");
                        var mat = globalModel.VisionsModel.ImageDatas.Where(image => image.Name == ""图片名称"").FirstOrDefault();
                        imageControl.ShowMat(mat.Mat);
                        flow.Step++;
                    }
                    break;
                    ");
                    break;
                case "画线画圆":
                    CustomTextEditor.Insert(@"
                        case 3:
                        {
                            var imageControl = globalModel.GetCustomControl(""图像控件名"");
                            //画圆
                            imageControl.ShowEllipse(1000, 1000, 500, 500, Brushes.Green);

                            flow.Step++;
                        }  
                        break;
                        ");
                    break;
            }

        }

        public CustomTextEditor CustomTextEditor { get; set; }

        public void Demo(GlobalModel globalModel, FlowModel flow)
        {


            switch (flow.Step)
            {
                case 0:
                    {
                        var imageControl = globalModel.GetCustomControl("C1");
                        Path path = new()
                        {
                            StrokeThickness = 3,
                            Stroke = Brushes.Green//设置Path基础属性
                        };
                        var el = new EllipseGeometry
                        {
                            Center = new() { X = 100, Y = 200 },
                            RadiusX = 50,
                            RadiusY = 50
                        };
                        path.Data = el;
                        System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            var ui = imageControl.UIElement as ImageEdit;
                            ui.Draw(path);
                        }));

                        flow.Step++;
                    }

                    break;
            }


        }
    }
}
